<script lang="ts" setup>
  import { ref } from "vue"
  import gmDialog from '@/components/Dialog/index.vue'
  import { type FormInstance, type FormRules, ElMessage } from "element-plus"
  import { updatePassword } from '@/api/admin'

  const rules: FormRules = {
    oldPassword: [
      { required: true, message: '请输入旧密码', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    confirmPassword: [
      { required: true, message: '请确认密码', trigger: 'blur' },
      { validator: (rule, value, callback) => {
        if (value !== form.value.password) {
            callback(new Error('两次输入的密码不一致'));
        } else {
            callback();
        }
      }, trigger: 'blur' }
    ]
  }
  const form = ref<any>({})
  const dialogRef = ref<InstanceType<typeof gmDialog>>()
  const loading = ref<boolean>(true)
  const formRef = ref<FormInstance>()
  const emit = defineEmits(['cancel','success'])

  const cancel = () => {
    emit('cancel')
  }

  const success =  async(formEl: FormInstance | undefined)=>{
    dialogRef.value.setLoading(true)
    await formEl?.validate((valid) => {
      if (!valid) {
        dialogRef.value.setLoading(false)
        return
      }
      updatePassword(form.value).then(()=>{
         ElMessage({
            message: '操作成功',
            type: 'success',
          })
        emit('success')
      }).catch((e)=>{
        dialogRef.value.setLoading(false)
      })
    })
  }
</script>

<template>
  <gm-dialog
    ref="dialogRef"
    title="修改密码"
    @cancel="cancel"
    @comfirm="success(formRef)"
    v-loading="loading">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item prop="oldPassword" label="旧密码">
        <el-input v-model="form.oldPassword" type="password" placeholder="" />
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" type="password" placeholder="" />
      </el-form-item>
      <el-form-item prop="confirmPassword" label="确认密码">
        <el-input v-model="form.confirmPassword" type="password" placeholder="" />
      </el-form-item>
    </el-form>
  </gm-dialog>
</template>


<style lang="scss" scoped>
</style>
